import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import { Layout, Menu, Avatar, Dropdown, message } from 'antd';
import {
  DashboardOutlined,
  UserOutlined,
  FileTextOutlined,
  BankOutlined,
  ContainerOutlined,
  SettingOutlined,
  LogoutOutlined,
  TeamOutlined
} from '@ant-design/icons';
import './App.css';

// 页面组件
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import UserManagement from './pages/UserManagement';
import EmployerAudit from './pages/EmployerAudit';
import JobManagement from './pages/JobManagement';
import ContractManagement from './pages/ContractManagement';
import SettlementManagement from './pages/SettlementManagement';
import SystemSettings from './pages/SystemSettings';

const { Header, Sider, Content } = Layout;

// 菜单配置
const menuItems = [
  {
    key: '/dashboard',
    icon: <DashboardOutlined />,
    label: '数据看板',
  },
  {
    key: '/users',
    icon: <UserOutlined />,
    label: '用户管理',
  },
  {
    key: '/employers',
    icon: <TeamOutlined />,
    label: '用工方审核',
  },
  {
    key: '/jobs',
    icon: <BankOutlined />,
    label: '岗位管理',
  },
  {
    key: '/contracts',
    icon: <ContainerOutlined />,
    label: '合同管理',
  },
  {
    key: '/settlements',
    icon: <TeamOutlined />,
    label: '结算管理',
  },
  {
    key: '/settings',
    icon: <SettingOutlined />,
    label: '系统设置',
  },
];

function App() {
  const [collapsed, setCollapsed] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [selectedKey, setSelectedKey] = useState('/dashboard');
  const navigate = useNavigate();

  useEffect(() => {
    // 检查登录状态
    const token = localStorage.getItem('admin_token');
    const userInfo = localStorage.getItem('admin_user');
    
    if (token && userInfo) {
      setCurrentUser(JSON.parse(userInfo));
    } else {
      navigate('/login');
    }

    // 设置当前选中的菜单
    const currentPath = window.location.pathname;
    if (currentPath !== '/login') {
      setSelectedKey(currentPath);
    }
  }, [navigate]);

  // 登录成功回调
  const handleLoginSuccess = (userInfo, token) => {
    setCurrentUser(userInfo);
    localStorage.setItem('admin_token', token);
    localStorage.setItem('admin_user', JSON.stringify(userInfo));
    navigate('/dashboard');
  };

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem('admin_token');
    localStorage.removeItem('admin_user');
    setCurrentUser(null);
    message.success('退出登录成功');
    navigate('/login');
  };

  // 菜单点击
  const handleMenuClick = ({ key }) => {
    setSelectedKey(key);
    navigate(key);
  };

  // 用户下拉菜单
  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人信息',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  // 如果未登录，显示登录页面
  if (!currentUser && window.location.pathname !== '/login') {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  return (
    <div className="App">
      <Routes>
        <Route path="/login" element={<Login onLoginSuccess={handleLoginSuccess} />} />
        <Route path="/*" element={
          <Layout style={{ minHeight: '100vh' }}>
            <Sider 
              collapsible 
              collapsed={collapsed} 
              onCollapse={setCollapsed}
              theme="dark"
            >
              <div className="logo">
                <h2 style={{ color: 'white', textAlign: 'center', margin: '16px 0' }}>
                  {collapsed ? '招企' : '招企管理后台'}
                </h2>
              </div>
              <Menu
                theme="dark"
                mode="inline"
                selectedKeys={[selectedKey]}
                items={menuItems}
                onClick={handleMenuClick}
              />
            </Sider>
            
            <Layout>
              <Header style={{ 
                padding: '0 24px', 
                background: '#fff', 
                display: 'flex', 
                justifyContent: 'space-between',
                alignItems: 'center',
                boxShadow: '0 1px 4px rgba(0,21,41,.08)'
              }}>
                <div></div>
                <Dropdown
                  menu={{ items: userMenuItems }}
                  placement="bottomRight"
                >
                  <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
                    <Avatar icon={<UserOutlined />} style={{ marginRight: 8 }} />
                    <span>{currentUser?.realName || '管理员'}</span>
                  </div>
                </Dropdown>
              </Header>
              
              <Content style={{ 
                margin: '24px 16px', 
                padding: 24, 
                background: '#fff',
                borderRadius: 8
              }}>
                <Routes>
                  <Route path="/" element={<Navigate to="/dashboard" replace />} />
                  <Route path="/dashboard" element={<Dashboard />} />
                  <Route path="/users" element={<UserManagement />} />
                  <Route path="/employers" element={<EmployerAudit />} />
                  <Route path="/jobs" element={<JobManagement />} />
                  <Route path="/contracts" element={<ContractManagement />} />
                  <Route path="/settlements" element={<SettlementManagement />} />
                  <Route path="/settings" element={<SystemSettings />} />
                </Routes>
              </Content>
            </Layout>
          </Layout>
        } />
      </Routes>
    </div>
  );
}

export default App;
